package com.sky.bestserialhelper.ui;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.sky.bestserialhelper.R;
import com.sky.bestserialhelper.listener.OnIOTransferListener;
import com.sky.bestserialhelper.manager.TransferManager;
import com.sky.bestserialhelper.service.InfoTransferS;
import com.sky.bestserialhelper.utils.ByteUtil;

import java.io.IOException;

/**
 * Created by Administrator on 2017/12/27.
 */

public class InfoTransferA extends AppCompatActivity {

    public InfoTransferS infoTransferS;
    public Intent intent;
    public InfoTransferS.InfoTransferBinder binder;

    Button btnSend;

    private ServiceConnection connection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            binder = (InfoTransferS.InfoTransferBinder) service;
            infoTransferS = binder.getService();
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            Log.v(this.getClass().getName(),"connect close!!!");
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_info_transfer);

        intent = new Intent(InfoTransferA.this, InfoTransferS.class);
        bindService(intent, connection, Context.BIND_AUTO_CREATE);



        TransferManager.getInstance().setOnIOTransferListener(new OnIOTransferListener() {
            @Override
            public void onReceive(byte[] data, int size) {
                System.out.println("====>接收数据:"+ ByteUtil.byteArrayToString(data));
            }

            @Override
            public void onSerialConnect(boolean isConnected) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(InfoTransferA.this, "连接失败,请选择别的串口", Toast.LENGTH_SHORT).show();
                        InfoTransferA.this.finish();
                    }
                });
            }
        });

        btnSend = (Button) findViewById(R.id.btn_send);
        btnSend.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    binder.sendCommand(new byte[]{0x09,0x09,0x09,0x09,0x09,0x09,0x09});
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
//        TransferManager.getInstance().disConnect();
        unbindService(connection);
    }
}
